import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface GameState {
  isPlaying: boolean
  currentScene: string
  playerHealth: number
  playerLevel: number
  currentFloor: number
  score: number
}

export interface PlayerStats {
  health: number
  maxHealth: number
  mana: number
  maxMana: number
  attack: number
  defense: number
  speed: number
  experience: number
  level: number
}

export interface GameSettings {
  soundEnabled: boolean
  musicEnabled: boolean
  difficulty: 'easy' | 'normal' | 'hard'
  language: 'zh' | 'en'
}

export const useGameStore = defineStore('game', () => {
  // 游戏状态
  const gameState = ref<GameState>({
    isPlaying: false,
    currentScene: 'menu',
    playerHealth: 100,
    playerLevel: 1,
    currentFloor: 1,
    score: 0,
  })

  // 玩家属性
  const playerStats = ref<PlayerStats>({
    health: 100,
    maxHealth: 100,
    mana: 50,
    maxMana: 50,
    attack: 10,
    defense: 5,
    speed: 8,
    experience: 0,
    level: 1,
  })

  // 游戏设置
  const gameSettings = ref<GameSettings>({
    soundEnabled: true,
    musicEnabled: true,
    difficulty: 'normal',
    language: 'zh',
  })

  // 游戏进度
  const gameProgress = ref({
    unlockedCharacters: ['warrior'],
    unlockedEquipment: [],
    achievements: [],
    highestFloor: 1,
    totalPlayTime: 0,
    totalDeaths: 0,
  })

  // 计算属性
  const isGameActive = computed(() => gameState.value.isPlaying)
  const currentScene = computed(() => gameState.value.currentScene)
  const playerHealthPercentage = computed(
    () => (playerStats.value.health / playerStats.value.maxHealth) * 100,
  )
  const playerManaPercentage = computed(
    () => (playerStats.value.mana / playerStats.value.maxMana) * 100,
  )

  // 游戏状态管理
  function startGame() {
    gameState.value.isPlaying = true
    gameState.value.currentScene = 'game'
    gameState.value.currentFloor = 1
    gameState.value.score = 0
    resetPlayerStats()
  }

  function pauseGame() {
    gameState.value.isPlaying = false
  }

  function resumeGame() {
    gameState.value.isPlaying = true
  }

  function endGame() {
    gameState.value.isPlaying = false
    gameState.value.currentScene = 'menu'
    updateGameProgress()
  }

  function switchScene(sceneName: string) {
    gameState.value.currentScene = sceneName
  }

  // 玩家属性管理
  function resetPlayerStats() {
    playerStats.value = {
      health: 100,
      maxHealth: 100,
      mana: 50,
      maxMana: 50,
      attack: 10,
      defense: 5,
      speed: 8,
      experience: 0,
      level: 1,
    }
  }

  function updatePlayerHealth(health: number) {
    playerStats.value.health = Math.max(0, Math.min(health, playerStats.value.maxHealth))
    if (playerStats.value.health <= 0) {
      handlePlayerDeath()
    }
  }

  function updatePlayerMana(mana: number) {
    playerStats.value.mana = Math.max(0, Math.min(mana, playerStats.value.maxMana))
  }

  function addExperience(exp: number) {
    playerStats.value.experience += exp
    checkLevelUp()
  }

  function checkLevelUp() {
    const expNeeded = playerStats.value.level * 100
    if (playerStats.value.experience >= expNeeded) {
      levelUp()
    }
  }

  function levelUp() {
    playerStats.value.level++
    playerStats.value.experience -= playerStats.value.level * 100
    playerStats.value.maxHealth += 20
    playerStats.value.maxMana += 10
    playerStats.value.attack += 2
    playerStats.value.defense += 1
    playerStats.value.speed += 1

    // 恢复满血满蓝
    playerStats.value.health = playerStats.value.maxHealth
    playerStats.value.mana = playerStats.value.maxMana
  }

  function handlePlayerDeath() {
    gameProgress.value.totalDeaths++
    endGame()
  }

  // 游戏进度管理
  function updateGameProgress() {
    if (gameState.value.currentFloor > gameProgress.value.highestFloor) {
      gameProgress.value.highestFloor = gameState.value.currentFloor
    }
  }

  function unlockCharacter(characterName: string) {
    if (!gameProgress.value.unlockedCharacters.includes(characterName)) {
      gameProgress.value.unlockedCharacters.push(characterName)
    }
  }

  function unlockEquipment(equipmentName: string) {
    if (!gameProgress.value.unlockedEquipment.includes(equipmentName)) {
      gameProgress.value.unlockedEquipment.push(equipmentName)
    }
  }

  function unlockAchievement(achievementName: string) {
    if (!gameProgress.value.achievements.includes(achievementName)) {
      gameProgress.value.achievements.push(achievementName)
    }
  }

  // 游戏设置管理
  function updateSettings(settings: Partial<GameSettings>) {
    gameSettings.value = { ...gameSettings.value, ...settings }
    saveSettings()
  }

  function saveSettings() {
    localStorage.setItem('gameSettings', JSON.stringify(gameSettings.value))
  }

  function loadSettings() {
    const saved = localStorage.getItem('gameSettings')
    if (saved) {
      try {
        gameSettings.value = { ...gameSettings.value, ...JSON.parse(saved) }
      } catch (error) {
        console.error('Failed to load settings:', error)
      }
    }
  }

  // 分数管理
  function addScore(points: number) {
    gameState.value.score += points
  }

  function setScore(points: number) {
    gameState.value.score = points
  }

  // 楼层管理
  function advanceFloor() {
    gameState.value.currentFloor++
    updateGameProgress()
  }

  function setFloor(floor: number) {
    gameState.value.currentFloor = floor
    updateGameProgress()
  }

  // 初始化
  function initialize() {
    loadSettings()
    console.log('Game store initialized')
  }

  return {
    // 状态
    gameState,
    playerStats,
    gameSettings,
    gameProgress,

    // 计算属性
    isGameActive,
    currentScene,
    playerHealthPercentage,
    playerManaPercentage,

    // 游戏状态管理
    startGame,
    pauseGame,
    resumeGame,
    endGame,
    switchScene,

    // 玩家属性管理
    resetPlayerStats,
    updatePlayerHealth,
    updatePlayerMana,
    addExperience,
    levelUp,

    // 游戏进度管理
    updateGameProgress,
    unlockCharacter,
    unlockEquipment,
    unlockAchievement,

    // 游戏设置管理
    updateSettings,
    saveSettings,
    loadSettings,

    // 分数和楼层管理
    addScore,
    setScore,
    advanceFloor,
    setFloor,

    // 初始化
    initialize,
  }
})
